layui.define(['form', 'zadmin','layer'], function(exports) {
    var form = layui.form,
        $ = layui.jquery,
        zadmin = layui.zadmin,
        layer = layui.layer;

    function makeItem(title = '设置项名称', setkey = '', setvalue = '', is_system = 0, type = 'text', setting = '') {
        var code = $('#formDemo').prop("outerHTML");
        code.id = null;
        code = code
            .replace('{title}', title)
            .replace('{setkey}', setkey)
            .replace('{is_system}', is_system)
            .replace('{setting}', setting)

        //判断类别
        var fieldCode,
            buttons = { 'set': false, 'tips': false };
        if (type == 'text' || type == 'number' || type == 'password') {
            //文本框或数字或密码
            fieldCode = '<input name="setvalue[]" class="layui-input" type="' + type + '" value="' + setvalue + '">';
        } else if (type == 'textarea') {
            //多行文本
            fieldCode = '<textarea name="setvalue[]" class="layui-textarea">' + setvalue + '</textarea>';
        } else if (type == 'switch') {
            fieldCode = '<input type="checkbox" value="1" name="setvalue[]" lay-skin="switch" ' + (setvalue == 1 ? 'checked=""' : '') + '>';
        } else if (type == 'multiSelect' || type == 'select') {
            fieldCode = '<div id="multiSelect_' + Math.ceil(Math.random() * 10000) + '" class="xm-select-demo" data-value="' + setvalue + '"></div>';
            buttons.set = true;
        }
        code = code.replace('{field}', fieldCode);

        code = $(code);
        code.find('option[value="' + type + '"]').attr("selected", "");
        if (is_system == 1) {
            code.find('.layui-icon-delete').parent().addClass('layui-btn-disabled').attr('disabled', true).attr('title', '系统设置项不可删除');
            code.find('input[name^="title"]').addClass('layui-disabled').attr('disabled', true);
            code.find('input[name^="setkey"]').addClass('layui-disabled').attr('disabled', true);
            code.find('select[name^="type"]').addClass('layui-disabled').attr('disabled', true);
            buttons.set = false;
        }
        for (var x in buttons) {
            if (!buttons[x]) {
                code.find('.layui-icon-' + x).parent().remove();
            }
        }
        code.removeClass('hide');
        return code;
        $('#add').before(code);
    }

    function formRender() {
        var multis = $('.xm-select-demo');
        multis.each(function(n) {
            var item = $(this.parentNode.parentNode.parentNode.parentNode); //当前元素
            var setting = item.find('input[name^="setting"]').val(); //获取所有的设置项
            var values = this.dataset.value.split(',');
            var data = [];
            if (setting.length > 0) {
                var settings = setting.split(',');
                for (var i = 0; i < settings.length; i++) {
                    var value = settings[i].split('|');
                    if (value.length == 1) value[1] = value[0];
                    data.push({ name: value[1], value: value[0], selected: values.indexOf(value[0]) >= 0 })
                }
            }
            var that = this;
            xmSelect.render({
                el: '#' + this.id,
                name: 'setvalue[]',
                data: data,
                radio: item.find('select[name^="type"]').val() == 'select',
                on: function(data) {
                    var arr = data.arr;
                    var newData = [];
                    data.arr.forEach(function(n) {
                        newData.push(n.value);
                    })
                    that.dataset.value = newData.join(',');
                },
            })
        })
        form.render();
        //监听表单操作
        $('.layui-icon').parent('.layui-btn').click(function() {
            var op = $(this).children('.layui-icon')[0].classList[1].substr(('layui-icon-').length);
            var item = $(this.parentNode.parentNode.parentNode.parentNode.parentNode);
            if (op == 'up') {
                var prevItem = item.prev();
                prevItem.before(item.prop("outerHTML"));
                item.remove();
                formRender();
            } else if (op == 'down') {
                var nextItem = item.next();
                nextItem.after(item.prop("outerHTML"));
                item.remove();
                formRender();
            } else if (op == 'delete') {
                layer.confirm('您确定要删除这个设置项目吗？', { icon: 3, title: '操作确认' }, function(layerindex) {
                    item.remove();
                    formRender();
                    layer.close(layerindex);
                });
            } else if (op == 'set') {
                var setting = item.find('input[name^="setting"]').val();
                var code = '<table class="layui-table"><colgroup><col width="60"><col width="200"><col width="200"></colgroup><thead><tr><th></th><th>值</th><th>文本</th></tr></thead><tbody id="settingdata">';
                if (setting.length > 0) {
                    var settings = setting.split(',');
                    settings.forEach(function(n) {
                        var value = n.split('|');
                        code += '<tr>';
                        code += '<td><button class="layui-btn delitem" type="button">删除</button></td>';
                        code += '<td><input type="text" name="value[]" value="' + (value[0]) + '" required autocomplete="off" class="layui-input"></td>';
                        code += '<td><input type="text" name="text[]" value="' + (value[1] ? value[1] : '') + '" autocomplete="off" class="layui-input"></td>';
                        code += '</tr>';
                    })
                }
                code += '</tbody></table>';

                function delrender() {
                    $('.delitem').click(function() {
                        $(this.parentNode.parentNode).remove();
                    })
                }

                layer.open({
                    title: '文本框内容请勿填写\'",|，若不填写文本内容，则文本内容为值',
                    content: code,
                    btn: ['保存', '新增'],
                    area: ['500px', '350px'],
                    yes: function(layerindex, layero) {
                        var values = $('input[name^="value"]');
                        var texts = $('input[name^="text"]');
                        var datas = [];
                        for (var i = 0; i < values.length; i++) {
                            if (values[i].value.length <= 0) {
                                values[i].focus();
                                return;
                            }
                            datas.push(values[i].value + (texts[i].value.length > 0 ? ('|' + texts[i].value) : ''));
                        }
                        item.find('input[name^="setting"]').val(datas.join(','));
                        formRender();
                        layer.close(layerindex);
                    },
                    success: function() {
                        delrender();
                    },
                    btn2: function(index, layero) {
                        var code = '<tr>';
                        code += '<td><button class="layui-btn delitem" type="button">删除</button></td>';
                        code += '<td><input type="text" name="value[]" required autocomplete="off" class="layui-input"></td>';
                        code += '<td><input type="text" name="text[]" autocomplete="off" class="layui-input"></td>';
                        code += '</tr>';
                        $('#settingdata').append(code);
                        delrender();
                        return false;
                    }
                });
            }
        })


    }
    var loadingIndex = zadmin.loading();
    $.get(window.location.href, {}, function(res) {
        layer.close(loadingIndex);
        $('#add').prevAll().remove();
        for (var i = 0; i < res.data.length; i++) {
            $('#add').before(makeItem(res.data[i].title, res.data[i].setkey, res.data[i].setvalue, res.data[i].is_system, res.data[i].type, res.data[i].setting));
        }
        formRender();
    })
    form.on('select(type)', function(data) {
        var elem = data.elem,
            value = data.value,
            othis = data.othis;
        var ele = $(elem.parentNode.parentNode.parentNode.parentNode);
        var code = makeItem(ele.find('input[name^="title"]').val(), ele.find('input[name^="setkey"]').val(), ele.find('[name^="setvalue"]').val(), ele.find('input[name^="is_system"]').val(), ele.find('select[name^="type"]').val(), ele.find('input[name^="setting"]').val());
        ele.html(code[0].innerHTML);
        formRender();
    });

    $('#add').click(function() {
        //重载监听事件
        $(this).before(makeItem());
        formRender();
    })
    //formRender();

    form.on('submit(save)', function(data) {
        var loadingIndex = zadmin.loading();
        $.post(window.location.href, data.field, function(res) {
            layer.close(loadingIndex);
            zadmin.showReturn(res, function(res) {
                $('#add').prevAll().remove();
                for (var i = 0; i < res.data.length; i++) {
                    $('#add').before(makeItem(res.data[i].title, res.data[i].setkey, res.data[i].setvalue, res.data[i].is_system, res.data[i].type, res.data[i].setting));
                }
                formRender();
            })
        })
        return false;
    })
    exports('site', {})
})